<template>
  <div class="messages-container">
    <a-button type="text" @click="goBack" style="margin-right: 16px">
      <template #icon><arrow-left-outlined /></template>
      返回
    </a-button>
    <a-card :bordered="false" title="我的消息" class="messages-card">
      <template #title>
        <div class="card-title">
          <a-button type="link" class="back-button" @click="router.back()">
            <arrow-left-outlined />
          </a-button>
          <span>我的消息</span>
        </div>
      </template>

      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="invitation" tab="面试邀请">
          <a-list
            class="message-list"
            :data-source="invitations"
            :loading="loading"
            item-layout="horizontal"
            :pagination="{ pageSize: 10, hideOnSinglePage: true }"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :style="{ backgroundColor: '#108ee9' }">R</a-avatar>
                  </template>
                  <template #title>
                    <div class="message-title">
                      <span>【面试邀请】{{ item.company }}{{ item.position }}岗位</span>
                    </div>
                  </template>
                  <template #description>
                    <div class="message-content">
                      <div class="message-preview">恭喜您通过全流程模拟面试，{{ item.company }}邀请您参加真实面试。</div>
                      <div class="message-time">{{ item.createTime }}</div>
                    </div>
                  </template>
                </a-list-item-meta>
                <div class="invitation-actions">
                  <a-button
                    type="primary"
                    @click="acceptInvitation(item)"
                    :disabled="item.isAccepted !== 0"
                    v-if="item.isAccepted === 0"
                  >
                    接受
                  </a-button>
                  <a-button
                    @click="declineInvitation(item)"
                    :disabled="item.isAccepted !== 0"
                    style="margin-left: 8px"
                    v-if="item.isAccepted === 0"
                  >
                    拒绝
                  </a-button>
                  <a-tag v-if="item.isAccepted === 2" color="success">已接受</a-tag>
                  <a-tag v-if="item.isAccepted === 1" color="error">已拒绝</a-tag>
                  <a-button type="link" @click="viewMessageDetail(item)"> 查看详情 </a-button>
                </div>
              </a-list-item>
            </template>
            <template #empty>
              <div class="empty-container">
                <a-empty description="暂无面试邀请" />
              </div>
            </template>
          </a-list>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 消息详情弹窗 -->
    <a-modal
      v-model:visible="detailModalVisible"
      title="面试邀请详情"
      :footer="null"
      width="600px"
    >
      <template v-if="selectedMessage">
        <div class="message-detail-header">
          <div class="message-detail-avatar">
            <a-avatar
              :style="{ backgroundColor: '#108ee9', verticalAlign: 'middle' }"
              size="large"
            >
              R
            </a-avatar>
          </div>
          <div class="message-detail-info">
            <div class="message-detail-sender">
              {{ selectedMessage.company }}招聘团队
            </div>
            <div class="message-detail-time">
              {{ selectedMessage.createTime }}
            </div>
          </div>
        </div>

        <div class="message-detail-content">
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="邀请公司">{{
              selectedMessage.company
            }}</a-descriptions-item>
            <a-descriptions-item label="技术领域">{{
              selectedMessage.techField
            }}</a-descriptions-item>
            <a-descriptions-item label="面试岗位">{{
              selectedMessage.position
            }}</a-descriptions-item>
            <a-descriptions-item label="面试时间">{{
              selectedMessage.interviewTime
            }}</a-descriptions-item>
            <a-descriptions-item label="面试官">{{
              selectedMessage.interviewerName
            }}</a-descriptions-item>
            <a-descriptions-item label="腾讯会议码">
              <div class="meeting-code-container">
                <span class="meeting-code">{{ selectedMessage.txMeetingCode }}</span>
                <a-button
                  type="link"
                  size="small"
                  class="copy-btn"
                  @click="copyMeetingCode(selectedMessage.txMeetingCode)"
                >
                  <copy-outlined /> 复制
                </a-button>
              </div>
            </a-descriptions-item>
          </a-descriptions>

          <div class="invitation-response" v-if="selectedMessage.isAccepted === 0">
            <a-divider>请回复邀请</a-divider>
            <div class="invitation-buttons">
              <a-button type="primary" @click="acceptInvitation(selectedMessage)">
                接受邀请
              </a-button>
              <a-button style="margin-left: 16px" @click="declineInvitation(selectedMessage)">
                拒绝邀请
              </a-button>
            </div>
          </div>

          <div class="invitation-status" v-else>
            <a-divider>邀请状态</a-divider>
            <a-alert
              :type="selectedMessage.isAccepted === 2 ? 'success' : 'info'"
              :message="selectedMessage.isAccepted === 2 ? '您已接受此邀请' : '您已拒绝此邀请'"
              show-icon
            />
          </div>
        </div>

        <div class="message-detail-actions">
          <a-button @click="detailModalVisible = false">关闭</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined, CopyOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { acceptOnlineInterviewInviteUsingGet, userViewOnlineInterviewListUsingGet } from '@/api/commonController'

const router = useRouter()

// 消息选项卡
const activeTab = ref('invitation')

// 加载状态
const loading = ref(false)

// 面试邀请数据
const invitations = ref([])

// 消息详情弹窗
const detailModalVisible = ref(false)
const selectedMessage = ref(null)

const goBack = () => {
  router.go(-1)
}

// 查看消息详情
const viewMessageDetail = (item) => {
  selectedMessage.value = item
  detailModalVisible.value = true
}

// 复制会议码
const copyMeetingCode = (code) => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(code)
      .then(() => {
        message.success('会议码已复制到剪贴板')
      })
      .catch(() => {
        message.error('复制失败，请手动复制')
      })
  } else {
    // 兼容不支持 clipboard API 的浏览器
    const textarea = document.createElement('textarea')
    textarea.value = code
    textarea.style.position = 'fixed'
    textarea.style.opacity = '0'
    document.body.appendChild(textarea)
    textarea.select()

    try {
      const successful = document.execCommand('copy')
      if (successful) {
        message.success('会议码已复制到剪贴板')
      } else {
        message.error('复制失败，请手动复制')
      }
    } catch (err) {
      message.error('复制失败，请手动复制')
    }

    document.body.removeChild(textarea)
  }
}

// 接受面试邀请
const acceptInvitation = async (item) => {
  try {
    loading.value = true
    const response = await acceptOnlineInterviewInviteUsingGet({
      onlineInterviewId: item.id as any,
      isAccept: 2
    })

    if (response && response.data) {
      item.isAccepted = 2
      message.success('已接受面试邀请')
      // 重新获取最新数据
      await fetchOnlineInvitations()
    } else {
      message.error('接受邀请失败')
    }
  } catch (error) {
    console.error('接受邀请出错:', error)
    message.error('接受邀请出错')
  } finally {
    loading.value = false
  }
}

// 拒绝面试邀请
const declineInvitation = async (item) => {
  try {
    loading.value = true
    const response = await acceptOnlineInterviewInviteUsingGet({
      onlineInterviewId: item.id as any,
      isAccept: 1
    })

    if (response && response.data) {
      item.isAccepted = 1
      message.success('已拒绝面试邀请')
      // 重新获取最新数据
      await fetchOnlineInvitations()
    } else {
      message.error('拒绝邀请失败')
    }
  } catch (error) {
    console.error('拒绝邀请出错:', error)
    message.error('拒绝邀请出错')
  } finally {
    loading.value = false
  }
}

//发送请求获取线上面试邀请数据
const fetchOnlineInvitations = async () => {
  loading.value = true
  try {
    const response = await userViewOnlineInterviewListUsingGet()
    if (response && response.data) {
      invitations.value = response.data as any
      console.log('获取线上面试邀请成功:', response.data)
    } else {
      message.error('获取面试邀请失败')
    }
  } catch (error) {
    console.error('获取面试邀请出错:', error)
    message.error('获取面试邀请出错')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取消息
onMounted(async () => {
  await fetchOnlineInvitations()
})
</script>

<style scoped>
.messages-container {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.messages-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.message-list {
  margin-top: 16px;
}

.message-title {
  display: flex;
  align-items: center;
}

.message-title span {
  margin-right: 8px;
  font-weight: 500;
}

.message-content {
  display: flex;
  flex-direction: column;
}

.message-preview {
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 500px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.message-actions,
.invitation-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.empty-container {
  padding: 32px 0;
}

/* 消息详情样式 */
.message-detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.message-detail-avatar {
  margin-right: 16px;
}

.message-detail-info {
  flex: 1;
}

.message-detail-sender {
  font-weight: 500;
  font-size: 16px;
  margin-bottom: 4px;
}

.message-detail-time {
  color: #999;
  font-size: 12px;
}

.message-detail-content {
  margin-bottom: 24px;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 4px;
}

.normal-message-content {
  white-space: pre-line;
  line-height: 1.6;
}

.invitation-response,
.invitation-status {
  margin-top: 24px;
}

.invitation-buttons {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

.message-detail-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* Add styles for the back button */
.card-title {
  display: flex;
  align-items: center;
}

.back-button {
  margin-right: 12px;
  font-size: 18px;
  padding: 0;
  color: #1890ff;
}

.meeting-code-container {
  display: flex;
  align-items: center;
}

.meeting-code {
  margin-right: 8px;
}

.copy-btn {
  padding: 0;
}
</style>
